<?php

namespace EthanZ\LaravelExt\Models\Traits;

use EthanZ\LaravelExt\Constants\CommonSetting;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

/**
 * 自定义分页
 *
 * @package EthanZ\LaravelExt\Models\Traits
 */
trait Page
{



    /**
     * 自定义分页（不适用大数据）
     *
     * @param Builder $query 查询.
     *
     * @return array
     */
    public function scopePage(Builder $query): array
    {
        $paginated = $query->paginate(request('page_size', CommonSetting::PAGE_SIZE));

        return [
            'list'  => $paginated->items(),
            'total' => $paginated->total(),
        ];
    }


    /**
     * 获取分页列表
     *
     * @param Builder $query
     *
     * @return object
     */
    public function scopePageList(Builder $query): object
    {
        return $query->forPage(request('page', 1), request('page_size', CommonSetting::PAGE_SIZE))->get();
    }


    /**
     * 获取总条数
     *
     * @param Builder $query
     *
     * @return int
     */
    public function scopePageCount(Builder $query): int
    {
        return $query->toBase()->getCountForPagination([Db::raw(1)]);
    }
}